import { Component } from 'react';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { debounce } from '@/utils/utils';
// import searchProduct from '@/mock/searchProduct.json';
import SearchBar from '@/components/SearchBar/index';
import { getSearchTop10, getSearchData } from '@/service/apis/home';
import { globalStore } from '@/store';
import GoodsList from './components/GoodsList/index';
import History, { getLocalHistory } from './components/History/index';
import './index.scss';

const setLocalHistory = (value) => {
  const history = getLocalHistory();
  if (!history.find((item) => item === value)) {
    history.push(value);
    Taro.setStorageSync('searchHistory', history.join(','));
  }
};

export default class Index extends Component {
  state = {
    productList: [],
    serviceList: [],
    searched: false,
    searchValue: '',
    historyData: {
      goods: [],
      service: [],
    },
  };
  componentDidMount = async () => {
    this.getSearchTop10();
  };

  getSearchTop10 = async () => {
    try {
      const { data } = await getSearchTop10({
        store_name: globalStore.currentShop.store_name,
      });
      this.setState({
        historyData: data,
      });
      console.log('data', data);
    } catch (err) {
      console.log('err', err);
      Taro.showToast({
        title: err.message,
        icon: 'none',
      });
    }
  };

  getSearchData = async (value: string) => {
    try {
      const { data } = await getSearchData({
        store_name: globalStore.currentShop.store_name,
        search_key: value,
      });
      this.setState({
        productList: data.goods,
        serviceList: data.services,
      });
      console.log('data', data);
    } catch (err) {
      console.log('err', err);
      Taro.showToast({
        title: err.message,
        icon: 'none',
      });
    }
  };

  onInputChange = (value: string) => {
    console.log('value: ', value);
    if (!value) {
      this.onClear();
      return;
    }
    setLocalHistory(value);
    this.getSearchData(value);
    this.setState({
      searched: true,
      // productList: searchProduct.data.list,
    });
  };

  onHandleHistory = (str: string) => {
    this.setState({
      searched: true,
      // productList: searchProduct.data.list,
      searchValue: str,
    });
    this.getSearchData(str);
  };

  onClear = () => {
    this.setState({
      productList: [],
      searched: false,
    });
  };

  getProductList = async () => {};
  render() {
    const { productList, searched, searchValue, historyData, serviceList } = this.state;
    return (
      <View className="home-wrap">
        <SearchBar searchValue={searchValue} onChange={debounce(this.onInputChange, 500)} />
        {searched ? (
          <GoodsList productList={productList} />
        ) : (
          <History historyData={historyData} onHandle={this.onHandleHistory} />
        )}
      </View>
    );
  }
}
